#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const cheerio = require('cheerio');
const Mustache = require('mustache');

const compDir = './src/editor/scene/comp/form';
const tplDir = './src/core/core/comp/form/';

function generatorIcon(answers) {
    const { category } = answers;
    const iconHTMLFile = `./src/editor/scene/template/templateElement/tplEasyForm/type/${category}/${category}.html`;
    const data = fs.readFileSync(path.resolve('./cli/template/leftIcon/leftIcon.html'));
    const output = Mustache.render(data.toString(), answers);
    const iconHTMLData = fs.readFileSync(iconHTMLFile);
    const $ = cheerio.load(iconHTMLData.toString());
    $('.form-contact').append($(output));
    fs.writeFileSync(path.resolve(iconHTMLFile), $('body').html());
}

function compWriteInEntry(answers) {
    const url = './src/editor/scene/comp/index.js';
    const data = fs.readFileSync(url, 'utf8').split('\n');
    data.splice(data.length - 2, 0, `    require('./form/${answers._type}'),`);
    fs.writeFileSync(url, data.join('\n'), 'utf8');
}

// 生成画布中的组件
function generatorComp(answers) {
    fs.mkdirSync(`${compDir}/${answers._type}`);
    fs.readdir('./cli/template/components', (err, files) => {
        if (err) {
            console.log('err====', err);
        }
        files.forEach(file => {
            const data = fs.readFileSync(`./cli/template/components/${file}`);
            const output = Mustache.render(data.toString(), answers);
            const fileName = file === 'test.directive.js' ? `${answers._type}.directive.js` : file;
            fs.writeFileSync(`${compDir}/${answers._type}/${fileName}`, output);
        });
    });
    compWriteInEntry(answers);
}

function tplWriteInEntry(answers) {
    const compMapUrl = './src/core/core/comp/CompMap.js';
    const compNamesUrl = './src/core/core/comp/CompNames.js';
    const longCompNameUrl = './src/editor/scene/page/longPageManager/longCompName.js';
    const CompName = answers.type.slice(3);

    // 写入CompMap.js
    const compMapUrlData = fs.readFileSync(compMapUrl, 'utf8').split('\n');
    compMapUrlData.splice(0, 0, `import ${CompName} from './form/${answers._type}';`);
    compMapUrlData.splice(compMapUrlData.length - 2, 0, `    ${answers.type}: ${CompName},`);
    fs.writeFileSync(compMapUrl, compMapUrlData.join('\n'), 'utf8');

    // 写入CompNames.js
    const compNameData = fs.readFileSync(compNamesUrl, 'utf8').split('\n');
    compNameData.splice(
        compNameData.length - 4,
        0,
        `    { name: '${answers.name}', types: ['${answers.type}'] },`
    );
    fs.writeFileSync(compNamesUrl, compNameData.join('\n'), 'utf8');

    // 写入longCompName.js
    const longCompNameData = fs.readFileSync(longCompNameUrl, 'utf8').split('\n');
    longCompNameData.splice(
        longCompNameData.length - 4,
        0,
        `    ${answers.type}: '${answers.name}',`
    );
    fs.writeFileSync(longCompNameUrl, longCompNameData.join('\n'), 'utf8');
}

// 生成组件vue入口
function generatorTpl(answers) {
    fs.mkdirSync(`${tplDir}/${answers._type}`);
    fs.readdir('./cli/template/tpl', (err, files) => {
        if (err) {
            console.log('err====', err);
        }
        files.forEach(file => {
            const data = fs.readFileSync(`./cli/template/tpl/${file}`);
            const output = Mustache.render(data.toString(), answers);
            fs.writeFileSync(`${tplDir}/${answers._type}/${file}`, output);
        });
    });
    tplWriteInEntry(answers);
}

inquirer
    .prompt([
        {
            type: 'list',
            name: 'category',
            message: '组件所属的分类',
            default: 'market',
            choices: [
                'blank (填空题)',
                'choose (选择题)',
                'header (表头组件)',
                'market (营销组件)',
                'other (其它题型)',
                'personalInfo (个人信息)',
                'reservation (预约登记)',
                'score (评分题)',
                'shop (商品组件)',
                'vote (投票组件)',
            ],
            filter(val) {
                return val.split(' ')[0];
            },
        },
        {
            type: 'input',
            name: 'name',
            message: '左侧图标所显示的组件名称',
        },
        {
            type: 'input',
            name: 'type',
            message: '组件type(请以eqx开头，并用驼峰命名)',
        },
        {
            type: 'input',
            name: 'icon',
            message: '左侧图片url(先将图片用cosbrowser上传CDN)',
        },
    ])
    .then(answers => {
        answers._type = answers.type.slice(3).toLowerCase();
        generatorIcon(answers);
        generatorComp(answers);
        generatorTpl(answers);
    });
